﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using S9Engine;


public partial class RoomGallery : Parser
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            InitAll();

            Session["CurrentPage"] = "RoomGalery.aspx";

            if (!CheckLogin()) Response.Redirect("login.aspx");
            _parser.SetCurrentDir("~/html");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            string type = Request["type"] ?? "default";
            string str = Request["object"] != null ? Request["object"].ToString() : "spot";
            string crroomDetailsID = Request["did"] != null ? Request["did"].ToString() : "0";
            _parser.Assign("crroomDetailsType", str);
            _parser.Assign("crroomDetailsID", crroomDetailsID);

            _DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Products);

            switch (type)
            {
                case "default":
                    {                        
                        //LoadFile("gallery_add.html", false);
                        //LoadRoomGallery();
                        //break;
                        Response.Redirect("RoomGallery.aspx?type=edit&id=0");
                        break;
                        //goto case "edit";
                    }
                case "add":
                    {
                        LoadFile("gallery_add.html", false);
                        LoadRoomGalleryByID(null);                    
                        break;
                    }
                case "edit":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("RoomGallery.aspx");
                        }
                        else
                        {
                            LoadFile("gallery_add.html", false);
                            _parser.Assign("crgalleryID", Request["id"].ToString());                                                        
                            LoadRoomGalleryByID(long.Parse(Request["id"]));                            
                        }
                        break;
                    }
                case "delete":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("RoomGallery.aspx");
                        }
                        else
                        {
                            DeleteRoomGalleryByID(long.Parse(Request["id"]));
                            Response.Redirect("RoomGallery.aspx");
                        }
                        break;
                    }
                default: goto case "default";
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void LoadRoomGallery()
    {
        try
        {
            List<Rooms> gallerys = _DR.Rooms.Where(g => g.LanguageCode.Equals(_currentLanguage)).OrderByDescending(g => g.ID).ToList();

            string search = Request["search"] ?? string.Empty;

            if (!string.IsNullOrEmpty(search))
            {
                gallerys = gallerys.Where(
                    p => p.Name.ToLower().Contains(search.ToLower()) ||
                    p.GroupName.ToLower().Contains(search.ToLower()) ||
                    p.Image.ToString().Equals(search) ||                    
                    _DR.RoomDetails.Where(m => m.Type.Equals("Spot")&& m.Value.Contains(search)).Count() > 0).ToList();
                _parser.Assign("searchValue", search);
            }

            double totalRecord = gallerys.Count();
            int page = int.Parse(Request["page"] ?? "1");
            int pageSize = _rowsPerPage;
            int totalPage = (int)(totalRecord / pageSize);

            if (totalPage * pageSize < totalRecord) totalPage++;

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * pageSize));
                int endRecord = (int)(page * pageSize > totalRecord ? totalRecord : page * pageSize);
                string galleryCode = string.Empty;
                long galleryID = 0;

                for (int i = startRecord; i < endRecord; i++)
                {
                    galleryID = gallerys[i].ID;                    

                    _parser.Assign("galleryID", gallerys[i].ID.ToString());
                    _parser.Assign("galleryImage", gallerys[i].Image);
                    _parser.Assign("galleryGroup", gallerys[i].GroupName);
                    _parser.Assign("galleryName", gallerys[i].Name);
                    
                    _parser.Parse("Main.Content.Table.TableItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / _pageRange;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % _pageRange == (_pageRange - 1) && page > _pageRange)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * _pageRange == 0 ? 1 : pagingPage * _pageRange);
                    }

                    endPage = (startPage + (_pageRange - 1) > totalPage ? totalPage : startPage + (_pageRange - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());


                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("currentPageStyle", page == i ? " class=\"current\"" : string.Empty);

                        if (!string.IsNullOrEmpty(search)) _parser.Assign("searchInfo", string.Format("&search={0}", search));

                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.Content.Table.Paging.PagingItem");
                    }

                    _parser.Parse("Main.Content.Table.Paging");

                }
                _parser.Parse("Main.Content.Table");
            }

            _parser.Parse("Main.Content");

            gallerys = null;
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LoadRoomGalleryByID(long? ID)
    {
        try
        {   
            if (ID == null) //AddNew
            {
                List<Rooms> rooms = _DR.Rooms.Where(r => r.LanguageCode.Equals(_currentLanguage)).ToList();
                foreach (Rooms r in rooms)
                {
                    _parser.Assign("slRoomID", r.ID.ToString());
                    _parser.Assign("slRoomName", r.Name);

                    _parser.Parse("Main.Content.EditForm.SelectRoom.SelectRoomItem");
                }
                _parser.Parse("Main.Content.EditForm.SelectRoom");

                _parser.Assign("galleryID", string.Empty);
                _parser.Assign("roomGroupName", string.Empty);
                _parser.Assign("roomName", string.Empty);
                _parser.Assign("roomImage", string.Empty);
                _parser.Assign("roomType", string.Empty);

                _parser.Assign("rx1", string.Empty);
                _parser.Assign("ry1", string.Empty);
                _parser.Assign("rx2", string.Empty);
                _parser.Assign("ry2", string.Empty);
                _parser.Assign("rDetailsValue", string.Empty);
                _parser.Assign("rDetailsContent", string.Empty);
                _parser.Assign("rDetailsLink", string.Empty);
                               
                _parser.Parse("Main.Content.EditForm.AddNew");
                _parser.Parse("Main.Content.EditForm.RoomDetails");
                _parser.Parse("Main.Content.EditForm");
                //_parser.Parse("Main.AddNewProducts");
            }
            else //Edit
            {
                //if (Request["object"] != "details")
                //{
                    //Rooms room = _DR.Rooms.Where(r => r.ID.Equals(ID.Value)).FirstOrDefault();
                    //if (room == null)
                    //{
                    //    _parser.Parse("Main.Content.Error");
                    //}
                    //else
                    //{
                        //List<Rooms> rooms = _DR.Rooms.Where(r => r.LanguageCode.Equals(_currentLanguage)).ToList();
                        //foreach (Rooms r in rooms)
                        //{
                        //    _parser.Assign("slRoomID", r.ID.ToString());
                        //    _parser.Assign("slRoomName", r.Name);

                        //    _parser.Parse("Main.Content.EditForm.SelectRoom.SelectRoomItem");
                        //}
                        //_parser.Parse("Main.Content.EditForm.SelectRoom");
                        //_parser.Assign("galleryID", room.ID.ToString());
                        //_parser.Assign("galleryGroup", room.GroupName);
                        //_parser.Assign("galleryName", room.Name);
                        //_parser.Assign("galleryImage", room.Image);

                        List<RoomDetails> roomDetails = _DR.RoomDetails.Where(r => r.Object.Equals(ID.Value)).OrderBy(r => r.Type).ThenByDescending(r => r.ID).ToList();

                        foreach (var dt in roomDetails)
                        {
                            _parser.Assign("roomDetailsID", dt.ID.ToString());
                            _parser.Assign("roomDetailsObject", dt.Object.ToString());
                            _parser.Assign("roomDetailsType", dt.Type);
                            _parser.Assign("roomDetailsValue", dt.Value);
                            _parser.Assign("roomDetailsContent", dt.Content);
                            _parser.Assign("roomDetailsLink", dt.Link);
                            _parser.Assign("roomCoordinates", dt.Coordinates);
                            _parser.Assign("galleryID", "0");

                            string[] tmp = dt.Coordinates.Split(',');
                            if (tmp.Length < 3)
                            {
                                _parser.Assign("x1", Fiter(tmp[0]));
                                _parser.Assign("y1", Fiter(tmp[1]));
                            }
                            else
                            {
                                _parser.Assign("x1", Fiter(tmp[0]));
                                _parser.Assign("y1", Fiter(tmp[1]));
                                _parser.Assign("x2", Fiter(tmp[2]));
                                _parser.Assign("y2", Fiter(tmp[3]));
                            }
                            _parser.Parse("Main.Content.EditForm.Type.TypeItem");
                        }
                        _parser.Parse("Main.Content.EditForm.Type");

                        _parser.Parse("Main.Content.EditForm.Edit");
                        //_parser.Assign("crgalleryID", ID.Value.ToString());
                        
                    //}

                    //room = null;
                //}
                //else {
                if(Request["did"]!=null && Request["did"]!="0"){
                    long did = long.Parse(Request["did"]);
                    if (did == 0) { }
                    else
                    {
                        RoomDetails roomDetail = _DR.RoomDetails.Where(r => r.LanguageCode.Equals(_currentLanguage) && r.ID.Equals(did)).FirstOrDefault();

                        _parser.Assign("rDetailsID", roomDetail.ID.ToString());
                        _parser.Assign("rDetailsObject", roomDetail.Object.ToString());
                        _parser.Assign("rDetailsType", roomDetail.Type);
                        _parser.Assign("rDetailsValue", roomDetail.Value);
                        _parser.Assign("rDetailsContent", roomDetail.Content);
                        _parser.Assign("rDetailsLink", roomDetail.Link);
                        _parser.Assign("rCoordinates", roomDetail.Coordinates);

                        string[] tmp = roomDetail.Coordinates.Split(',');
                        if (tmp.Length < 3)
                        {
                            _parser.Assign("rx1", Fiter(tmp[0]));
                            _parser.Assign("ry1", Fiter(tmp[1]));
                        }
                        else
                        {
                            _parser.Assign("rx1", Fiter(tmp[0]));
                            _parser.Assign("ry1", Fiter(tmp[1]));
                            _parser.Assign("rx2", Fiter(tmp[2]));
                            _parser.Assign("ry2", Fiter(tmp[3]));
                        }
                    }
                }
                _parser.Parse("Main.Content.EditForm.RoomDetails");
                _parser.Parse("Main.Content.EditForm");
            }
            
            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteRoomGalleryByID(long ID)
    {
        try
        {
            if (Request["object"] != "details")
            {
                Rooms room = _DR.Rooms.Where(r => r.ID.Equals(ID)).FirstOrDefault();

                if (room != null)
                {
                    _DR.DeleteObject(room);

                    List<RoomDetails> roomdetails = _DR.RoomDetails.Where(r => r.Object.Equals(ID)).ToList();

                    foreach (RoomDetails r in roomdetails)
                    {
                        _DR.DeleteObject(r);
                    }

                    _DR.SaveChanges();

                    roomdetails = null;
                }

                room = null;
            }
            else {
                RoomDetails rd = _DR.RoomDetails.Where(r => r.ID.Equals(ID)).FirstOrDefault();
                _DR.DeleteObject(rd);
                _DR.SaveChanges();

                rd = null;
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
    private string GetRequest(string key)
    {
        return Request[key] == null ? string.Empty : Server.UrlDecode(Request[key].ToString());
    }

    private string GetRequest(string key, string defaultValue)
    {
        return Request[key] == null || string.IsNullOrEmpty(Request[key]) ? defaultValue : Server.UrlDecode(Request[key].ToString());
    }    
}